package coursecase;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

//扫描指定⽬录，并找到名称或者内容中包含指定字符的所有普通⽂件
public class Test3 {
    public static void main(String[] args) {
        List<File> list = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入要查找的目录:");
        File file = new File(scanner.nextLine());
        if (!file.isDirectory()) {
            System.out.println("输入的路径不是目录，请重新输入");
            return;
        }
        System.out.println("请输入指定的字符:");
        String key = scanner.nextLine();
        seach(file,key,list);
        for (File file1 : list) {
            System.out.println(file1.getAbsolutePath());
        }

    }
    public static void seach(File dirFile,String key,List<File> list) {
        File[] files = dirFile.listFiles();
        if (files == null || files.length == 0) {
            return;
        }
        for (File file : files) {
            if (file.isDirectory()) {
                seach(file, key, list);
            } else {
                if (file.getName().contains(key) || isContentContains(file, key)) {
                    list.add(file);
                }
            }
        }

    }
    public static boolean isContentContains(File file,String key) {
        StringBuffer stringBuffer = new StringBuffer();
        try(InputStream inputStream = new FileInputStream(file)) {
            try(Scanner scanner = new Scanner(inputStream,"utf-8")) {
                if (scanner.hasNext()) {
                    stringBuffer.append(scanner.nextLine());
                    stringBuffer.append("\r\n");
                }
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuffer.indexOf(key) != -1;
    }
}
